<template>
	<ls-page title='订单'  :hidden="true"  :userIdentity='2' leftIcon='' :autoBack='false'>

		<view class="tabs-contianr">
			<TabList :list="tabList" v-model:activeIndex="activeIndex" @tabClick="handleTabClick" />
		</view>
		<scroll-view class="order-container-main" @scrolltolower="scrollToLower" scroll-y="{{true}}"
			lower-threshold="200">
			<view class="page-content">
				<view class="main-allItem" v-if="orderList.length">
					<view class="main-item" @click="toDetails(v)" v-for="(v, k) in orderList" :key="k">
						<view class="main-item-header">
							<view class="header-left">
								<view class="left-iconqnjg" v-if="themetype == '001' "></view>
								<view class="left-icon" v-if="themetype == '002' "></view>
								<view class="left-text">
									{{ v.orderTime }}
								</view>
							</view>
							<view class="header-right spe" v-if="v.state == '未支付'">
								待支付，剩余
								<van-count-down :time="v.timeDiff" format="mm : ss "
									@finish="timeOut(v.orderBatchCode)" />
							</view>
							<view class="header-right" v-else>
								{{ v.state }}
							</view>
						</view>

						<view class="main-item-center">
							<view class="center-li" style="padding-bottom: 40rpx">
								<view class="li-title">桌台号：</view>
								<view class="li-value">
									{{ v.roomName }}
								</view>
							</view>
							<view class="center-li">
								<view class="li-title">订单编号：</view>
								<view class="li-value">
									{{ v.payBatchCode }}
								</view>
							</view>
						</view>

						<view class="main-item-footer">
							<view class="footer-left">
								<view class="left-title">共1件，合计：</view>
								<view class="left-icon">￥</view>
								<view class="left-value">
									{{ v.totalAmt }}
								</view>
								<view class="left-float"></view>
							</view>
							<view class="footer-right" v-if="v.state != '已取消'">查看详情</view>
						</view>
					</view>
				</view>
				<view class="order-container-empty" v-else>
					<image v-if="themetype == '001' " class="empty-img" src="https://oss.jtmckj.com/h5-uniapp/qnig/my/i_icon_none.png"
						mode="aspectFill" />
						<image v-else class="empty-img" src="https://oss.jtmckj.com/wmp/kbq/order/i_icon_empty.png"
							mode="aspectFill" />
					<view class="empty-title">暂无订单，快去下单吧~</view>
					<view class="bottom-button" @click="toOrder">去下单</view>
				</view>

			</view>
		</scroll-view>

	</ls-page>
</template>

<script setup>
	import dayjs from 'dayjs';
	import {
		ref
	} from 'vue';
	import {
		HFiveMemberAppObjProcess
	} from '@/api/public.js'
	import wx from "weixin-js-sdk";
	import {
		_FormatNumber
	} from '@/until/tools';
	import {
		onLoad,
		onShow,
		onReachBottom
	} from '@dcloudio/uni-app';
	import {
		debounce,
		_ExtractParamsFromPath,
		getWeChatJsSDKConfig
	} from '@/until/tools.js'
     
	const themetype = uni.getStorageSync('themeInfo')?.type
	const SDKConfig = ref({})
	const orderList = ref([]);
	const tabList = reactive([{
			name: '今日订单'
		},
		{
			name: '历史订单'
		}
	]);
	const active = ref(0);
	const time = ref(1778763);
	const postForm = ref({
		dateType: '1', // 1今日 2历史
		pageSize: '15',
		pageIndex: '1'
	});
	const hasMore = ref(true);
	const url = ref('');
	const timeInt = ref(null);


	const activeIndex = ref(0);

	const actions = [{
			text: '按分类'
		},
		{
			text: '按获得时间'
		},
		{
			text: '按过期时间'
		},
	];

	// 跳转到订单详情
	const toDetails = (order) => {
		if(order.state == '已取消'){
			return
		}
		const id = order.orderBatchCode
		const state = order.state
		uni.navigateTo({
			// url: '/pagesOrder/view/pay/index?goodsList=' + encodeURIComponent(JSON.stringify(detailList)) + '&isPreVip=' + payTotalInfo.value.openVip
			url: `/subpkg/view/orderDetail/orderDetail?id=${id}&state=${state}` // 跳转到订单详情
		})
	}

	// 切换Tab的函数
	const handleTabClick = (e) => {
		active.value = e.index
		postForm.value.dateType = e.index === 0 ? '1' : '2' // 根据Tab切换日期类型
		getRocords(true) // 重新获取记录
	}

	// 倒计时结束处理
	const timeOut = (e) => {
		// return
		const id = e
		// 这里调用API逻辑来处理订单状态
		HFiveMemberAppObjProcess({
			functionName: 'CheckOrderState_H5',
			contentData: {
				orderBatchCode: id
			}
		}).then((res) => {
			console.log(res);
			if (!res.isPay) {

				HFiveMemberAppObjProcess({
					functionName: 'MemberOrderCancel_H5',
					contentData: {
						orderBatchCode: id,
						type: '1' // 0不显示取消记录 1 显示取消记录
					}
				}).then(() => {
					// 显示消息并重新获取记录
					uni.showToast({
						title: '已取消支付',
						mask: true,
						duration: 2000
					}).then(() => {
						getRocords(true)
					})
				})
			}
		})
	}

	const toOrder = () => {
		wx.config({
			debug: false, // 开启调试模式,
			appId: SDKConfig.value.appId, // 必填，企业号的唯一标识
			timestamp: SDKConfig.value.timestamp, // 必填，生成签名的时间戳
			nonceStr: SDKConfig.value.nonceStr, // 必填，生成签名的随机串
			signature: SDKConfig.value.signature, // 必填，签名
			jsApiList: ['scanQRCode'], // 必填，需要使用的JS接口列表
		});
		wx.ready((res) => {
			wx.scanQRCode({
				needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
				scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
				success: function(res) {
					// uni.$u.toast(JSON.stringify(res.resultStr))
					console.log(": res", res.resultStr);
					if (res.result) {
						const options = _ExtractParamsFromPath(res.result);
						if (!options.code) {
							uni.showToast({
								title: "二维码出错，请联系服务开台",
								icon: "none"
							});
							return
						}
						//以下数据存储字段暂无修改
						// uni.setStorageSync('ORG_CODE', options.org) // 可不用  
						// uni.setStorageSync('ROOM_CODE', options.code) // 可不用   
						shopInfo.value.orgCode = options.org;
						uni.setStorageSync('shopInfo', shopInfo.value);

						tableInfo.value.code = options.code;
						uni.setStorageSync('tableInfo', tableInfo.value);
						uni.navigateTo({
							url: '/pagesOrder/view/goods/index'
						})

					}
				},
				fail: function(response) {
					uni.showToast({
						title: "请扫描正确的二维码",
						icon: "none"
					});
				},
			});
		})
	}

	// 获取订单记录
	const getRocords = async (flag) => {
		if (flag) {
			postForm.value.pageIndex = '1'
			hasMore.value = true
		}
		try {
			const res = await HFiveMemberAppObjProcess({
				functionName: 'GetOrderRecord_H5',
				contentData: postForm.value
			})
			console.log(res);
			let formattedArray = res.map(obj => ({
				...obj,
				orderTime: dayjs(obj.orderTime).format('YYYY-MM-DD HH:mm:ss'),
				totalAmt: _FormatNumber(obj.totalAmt)
			}))
			formattedArray = formattedArray.map(obj => {
				const expireTime = dayjs(obj.expireTime).valueOf() 
				const now = dayjs().valueOf() 
				const timeDiffInMilliseconds = expireTime - now
				
				obj.timeDiff = timeDiffInMilliseconds
				
				return obj
			})
			console.log(formattedArray);
			orderList.value = formattedArray
			if (res.length < postForm.value.pageSize) {
				hasMore.value = false
			} else {
				hasMore.value = true
			}
		} catch (error) {
			console.error(error)
		}
	}

	// 触底加载更多

	// const onReachBottom = (e)=>{
	// 	console.log(e);
	// }
	const scrollToLower = (async () => {
		console.log('滚动');
		if (!hasMore.value) return
		console.log(11);
		postForm.value.pageIndex++
		try {
			const res = await HFiveMemberAppObjProcess({
				functionName: 'GetOrderRecord_H5',
				contentData: postForm.value
			})
			let formattedArray = res.map(obj => ({
				...obj,
				orderTime: dayjs(obj.orderTime).format('YYYY-MM-DD HH:mm:ss'),
				totalAmt: _FormatNumber(obj.totalAmt)
			}))
			formattedArray = formattedArray.map(obj => {
				const expireTime = new Date(obj.expireTime)
				const now = new Date()
				const timeDiffInMilliseconds = expireTime - now
				obj.timeDiff = timeDiffInMilliseconds
				return obj
			})
			if (res.length < postForm.value.pageSize) {
				hasMore.value = false
			} else {
				hasMore.value = true
			}
			orderList.value = [...orderList.value, ...formattedArray]
		} catch (error) {
			console.error(error)
		}
	})
	// 页面显示时调用
	onMounted(() => {
		
		getWeChatJsSDKConfig().then(resking => {
			SDKConfig.value = resking
		})
		// if (typeof getTabBar === 'function' && getTabBar()) {
		// 	getTabBar().setData({
		// 		selected: 2 // 设置 TabBar 的选中项
		// 	})
		// }
	})
	onShow(()=>{
		getRocords(true) // 初始化时获取记录
	})
</script>

<style lang="less" scoped>
	body {
		overflow: hidden;
	}

	::v-deep {
		.bac-f2 {
			overflow: hidden;
			// padding-bottom: 300rpx;
		}

		.page-view-tabbar {
			overflow: hidden;
		}
	}

	.tabs-contianr {
		background: var(--mainbaccolor);
		position: fixed;
		width: 100%;
		z-index: 10;
		box-sizing: border-box;
		padding: 0 139rpx 10rpx;
		// border-bottom: 1rpx solid var(--maincolorbd);
	}

	.order-container-main {
		height: 100%;
	}

	.page-content {
		padding: 10rpx 24rpx 200rpx;
	}

	.main-allItem {
		padding: 110rpx 0rpx;
		border-radius: 60rpx 60rpx 0 0;

		.main-item {
			background: #ffffff;
			border-radius: 16rpx;
			margin-bottom: 20rpx;

			.main-item-header {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 32rpx 24rpx 31rpx;
				border-bottom: 1px solid #f2f2f2f2;

				.header-left {
					display: flex;
					align-items: center;

					.left-icon {
						width: 36rpx;
						height: 36rpx;
						background-image: url('https://oss.jtmckj.com/wmp/kbq/common/i_icon_clock.png');
						background-size: 100% 100%;
						background-repeat: no-repeat;
						margin-right: 20rpx;
					}
					.left-iconqnjg {
						width: 36rpx;
						height: 36rpx;
						background-image: url('https://oss.jtmckj.com/h5-uniapp/qnig/booktable/time-icon.png');
						background-size: 100% 100%;
						background-repeat: no-repeat;
						margin-right: 20rpx;
					}

					.left-text {
						font-family: PingFang SC;
						font-weight: 500;
						font-size: 28rpx;
						color: var(--one--self--color);
						line-height: 28rpx;
					}
				}

				.header-right {
					font-family: PingFang SC;
					font-weight: 500;
					font-size: 26rpx;
					/* color: #FF3333;*/
					color: var(--third--self--color);
					line-height: 26rpx;
					display: flex;
					align-items: center;

					&.spe {
						color: #ff3333;
					}

					.van-count-down {
						font-family: PingFang SC;
						font-weight: 500;
						font-size: 26rpx;
						color: #ff3333;
						line-height: 26rpx;
					}
				}
			}

			.main-item-center {
				padding: 40rpx 24rpx;
				border-bottom: 1px solid #f2f2f2f2;

				.center-li {
					display: flex;
					align-items: center;
					font-family: PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					line-height: 28rpx;

					.li-title {
						color: var(--second--self--color);
					}

					.li-value {
						color: var(--second--self--color);
					}
				}
			}

			.main-item-footer {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 34rpx 24rpx 35rpx;

				.footer-left {
					display: flex;
					align-items: flex-end;
					font-family: PingFang SC;
					font-weight: 500;

					.left-title {
						font-size: 24rpx;
						color: #666666;
						line-height: 26rpx;
					}

					.left-icon {
						font-size: 24rpx;
						color: var(--one--self--color);
						line-height: 28rpx;
					}

					.left-value {
						font-size: 36rpx;
						color: var(--one--self--color);
						line-height: 36rpx;
					}

					.left-float {
						font-size: 24rpx;
						color: var(--one--self--color);
						line-height: 28rpx;
					}
				}

				.footer-right {
					font-family: PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: var(--maincolorf2);
					line-height: 28rpx;
					padding-right: 21rpx;
					position: relative;

					&::after {
						content: '';
						position: absolute;
						top: 4rpx;
						right: 0;
						width: 13rpx;
						height: 23rpx;
						background-image: url('https://oss.jtmckj.com/wmp/qnjg/common/i_icon_tra-right.png');
						background-size: 100% 100%;
						background-repeat: no-repeat;
					}
				}
			}
		}
	}

	.order-container-empty {
		padding-top: 144rpx;
		display: flex;
		flex-direction: column;
		/* justify-content: center;*/
		align-items: center;
		padding-bottom: 100rpx;

		.empty-img {
			width: 360rpx;
			height: 360rpx;
			margin: 0 auto;
		}

		.empty-title {
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: var(--maincolorf4);
			line-height: 32rpx;
			padding: 24rpx 0 58rpx;
		}

		.bottom-button {
			background: var(--dt-backcolorPink);
			border-radius: 40rpx;
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: var(--maincolor);
			line-height: 80rpx;
			text-align: center;
			width: 240rpx;
			height: 80rpx;
		}
	}
</style>